package soul.resource;

import soul.entity.User;
import soul.utils.Decript;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by sunzhengjie on 2016/11/17.
 */
@Controller
@RequestMapping("/wx")
public class WechatResource {

    private final String token = "furioussoulktoken";

    @RequestMapping
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始签名校验");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        List<String> array = new ArrayList<>();
        array.add(signature);
        array.add(timestamp);
        array.add(nonce);

        //排序
        String sortString = sort(token, timestamp, nonce);
        //加密
        String mytoken = Decript.SHA1(sortString);
        //校验签名
        if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
            System.out.println("签名校验通过。");
            try {
                response.getWriter().println(echostr); //如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("签名校验失败。");
        }
    }

    /**
     * 自动指定contentType和accept
     *
     * @param user
     * @param pathValue
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/test/{pathValue}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> doGet(@RequestBody User user, @PathVariable String pathValue) {
        Map<String, Object> mm = new HashMap<>();
        mm.put("id", user.getId());
        mm.put("usr", user);
        mm.put("pathValue", pathValue);
        return mm;
    }

    /**
     * 排序方法
     *
     * @param token
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);

        StringBuilder sbuilder = new StringBuilder();
        for (String str : strArray) {
            sbuilder.append(str);
        }

        return sbuilder.toString();
    }
}
